package com.zf.teacherservice.controller;

import com.zf.teacherservice.entity.Teacher;
import com.zf.teacherservice.repository.TeacherRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/teachers")
@RestController
@CrossOrigin
public class TeacherController {
    private final TeacherRepository teacherRepository;

    public TeacherController(TeacherRepository teacherRepository) {
        this.teacherRepository = teacherRepository;
    }

    @GetMapping("")
    public Map<String, Object> getTeachers(@RequestParam("currentPage") int currentPage,
                                           @RequestParam("pageSize") int pageSize) {
        int pageIndex = currentPage - 1;
        Pageable pageable = PageRequest.of(pageIndex, pageSize, Sort.by(Sort.Direction.DESC, "id"));
        Page<Teacher> teachers = this.teacherRepository.findAll(pageable);
        Map<String, Object> map = new HashMap();
        map.put("data", teachers.getContent());
        map.put("total", teachers.getTotalElements());
        map.put("pages", teachers.getTotalPages());
        return map;
    }

    @GetMapping("/{id}")
    public Teacher getTeacher(@PathVariable long id) {
        return this.teacherRepository.findById(id).get();
    }

    @PostMapping
    public ResponseEntity createTeacher(@RequestBody Teacher teacher) throws URISyntaxException {
        Teacher teacher1 = this.teacherRepository.save(teacher);
        return ResponseEntity.created(new URI("/teachers/" + teacher1.getId())).body(teacher1);
    }

    @PutMapping("/{id}")
    public ResponseEntity updateTeacher(@PathVariable Long id, @RequestBody Teacher teacher) {
        Teacher teacher1 = this.teacherRepository.findById(id).get();
        teacher1.setName(teacher.getName());
        teacher1.setEmail(teacher.getEmail());
        teacher1.setPhone(teacher.getPhone());
        teacher1.setGender(teacher.getGender());
        teacher1.setDescription(teacher.getDescription());

        this.teacherRepository.save(teacher1);
        return ResponseEntity.ok(teacher1);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteTeacher(@PathVariable Long id) {
        Teacher teacher1 = this.teacherRepository.findById(id).get();
        this.teacherRepository.delete(teacher1);
        return ResponseEntity.ok(teacher1);
    }
}
